package com.sinosoft.emplmis.application.web;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sinosoft.framework.core.api.domain.UserEntity;
import com.sinosoft.framework.core.api.service.UserService;
import com.sinosoft.framework.core.common.utils.StringUtil;

/**
 * 应用心跳程序控制器：用于保持会话连接应答、应用消息监听等场景
 * @author xiaoxiong
 *
 */
@Controller
@RequestMapping("application/heartbeat")
public class HeartbeatController {

	private Logger logger = LoggerFactory.getLogger(ResourceController.class.getName());
	
	@Autowired
	UserService userService;
	
	/**
	 * 保持会话连接应答
	 * @return
	 */
	@RequestMapping(value="/keepSessionLive", method = RequestMethod.GET)
	public @ResponseBody String keepSessionLive() {
		logger.info("保持会话连接应答成功!");
		return "true";
	}
	
	/**
	 * 屏保程序检验用户密码
	 * @return
	 */
	@RequestMapping(value="/checkPassword", method = RequestMethod.POST)
	public @ResponseBody Boolean checkPassword(String userName, String password) {
		if(StringUtil.isBlank(userName) || StringUtil.isBlank(password)) {
			logger.info("屏保程序检验用户密码失败,原因用户名或者密码为空!");
			return false;
		}
		UserEntity user = userService.queryUserInfoByLoginName(userName);
		if(userService.checkPassword(user, password) == true) {
			Session session = SecurityUtils.getSubject().getSession();
			session.setAttribute("userStatus", "alive");
			return true;
		} else {
			return false;
		}
	}
	
	/**
	 * 获取当前用户的状态:活动、睡眠
	 * @return
	 */
	@RequestMapping(value="/getCurrentUserStatus", method = RequestMethod.GET)
	public @ResponseBody String getCurrentUserStatus() {
		Session session = SecurityUtils.getSubject().getSession();
		return session.getAttribute("userStatus") == null?"alive" : session.getAttribute("userStatus").toString();
	}
	
	/**
	 * 设置当前用户为睡眠状态
	 */
	@RequestMapping(value="/setCurrentUserSleep", method = RequestMethod.GET)
	public @ResponseBody void setCurrentUserSleep() {
		Session session = SecurityUtils.getSubject().getSession();
		session.setAttribute("userStatus", "sleep");
	}
}
